var http = require('http')
var formidable = require('formidable')
var fs = require('fs')
var saveFile = require('./saveFile')

var server = http.createServer(function(req, res) {
	// 1 设置cors跨域
	res.setHeader('Access-Control-Allow-Origin', '*')
	res.setHeader('Access-Control-Allow-Headers', 'Content-Type')
	res.setHeader('Content-Type', 'application/json')

	// 2
	switch (req.method) {
		case 'OPTIONS':
			res.statusCode = 200
			res.end()
			break
		case 'POST':
			upload(req, res)
			break
	}
})

function upload(req, res) {
	// 1 判断
	if (!isFormData(req)) {
		res.statusCode = 200
		res.end('错误的请求, 请用multipart/form-data格式')
		return
	}

	// 2 处理
	var form = new formidable.IncomingForm()
	/* form.uploadDir = './myImage'
	form.keepExtensions = true */
	/* form.on('field', (field, value) => {
		console.log(field);
		console.log(value);
	});
	form.on('file', (name, file) => {
		console.log(name);
		console.log(file);
	}); */
	/* form.on('end', () => {
		res.end('上传完成!')
	}) */
	form.on('error', err => {
		res.statusCode = 500
		res.end('服务器内部错误!')
	})
	form.parse(req, function(err, fields, files) {
		saveFile('./file'+fields.name,()=>{
			// 初始化文件的读入流和文件的输出流
			let readStream = fs.createReadStream(files.file.filepath);
			let writeStream = fs.createWriteStream('./file'+fields.name);
			readStream.pipe(writeStream);
			// 监视文件状态，end为结束状态
			readStream.on('end', () => {
			  res.end('{"key":"上传成功"}')
			});
		})
	})
}

function isFormData(req) {
	let type = req.headers['content-type'] || ''
	return type.includes('multipart/form-data')
}

server.listen(8888)
// 终端打印如下信息
console.log('Server running at http://127.0.0.1:8888/');
